/**计算rem**/
(function(win){
    var remCalc = {};
    var docEl = win.document.documentElement,
        tid,
        hasRem = true;
    hasZoom = true;
    designWidth = 640;
    function refresh(){
        var width = docEl.getBoundingClientRect().width;
        if(hasRem){
            var rem = width/10;
            docEl.style.fontSize = rem + "px";
            remCalc.rem = rem;
            var actualSize = parseFloat(window.getComputedStyle(document.documentElement)["font-size"]);
            if(actualSize!== rem && actualSize>0 && Math.abs(actualSize-rem)>1){
                var remScaled = rem*rem/actualSize;
                docEl.style.fontSize = remScaled + "px";
            }
        }
        if(hasZoom){
            var style = document.getElementById('y_style');
            if(!style){
                style = document.createElement('style');
                style.id = 'y_style';
            }
            style.innerHTML = '._z{zoom:'+ width/designWidth + '}';
            document.getElementsByTagName('head')[0].appendChild(style);
        }
    }
    function dbcRefresh(){
        clearTimeout(tid);
        tid = setTimeout(refresh,100);
    }
    win.addEventListener("resize",function(){
        dbcRefresh()
    },false);
    win.addEventListener("pageshow",function(e){
        if(e.persisted){
            dbcRefresh()
        }
    },false);
    refresh();
    if(hasRem){
        remCalc.refresh = refresh;
        remCalc.rem2px = function(d){
            var val = parseFloat(d)/this.rem;
            if(typeof d==="string" && d.match(/px$/)){
                val+="rem";
            }
            return val
        };
        win.remCalc = remCalc;
    }
})(window);
function ImgLoadingByFile(imgArray,loadPageID,loadTxtID){
    if(sessionStorage.getItem("pageloaded")){
        $('#'+loadTxtID).html('100%');
        $('#'+loadPageID).fadeOut(1200);
        $('.swiper-wrapper').fadeIn(1200);
    }else{
        var imgLoad = 0;
        if(imgArray.length>0){
            var imgTotal = imgArray.length;
            var percent = 0;
            var img = [];
            for(var i = 0;i<imgArray.length;i++){
                img[i] = new Image();
                img[i].src=imgArray[i];
                img[i].onload = function(){
                    imgLoad++;
                    percent = parseInt(imgLoad/imgTotal*100);
                    $('#'+loadTxtID).html(percent+'%');
                    console.log(percent);
                    if(percent>=100){
                    	$('#'+loadPageID).fadeOut(1200);
                    	$('.swiper-wrapper').fadeIn(1200);
                        sessionStorage.setItem("pageloaded", "true");

                    }
                }
            }
        }
    }
}
$(function() {
//	alert(window.innerHeight);
	var imgFile = [
	    'img/loading.gif',
		'img/one/deng.png',
		'img/one/font.png',
		'img/one/one-bg.jpg',
		'img/one/one-text01.png',
		'img/one/one-text02.png',
		'img/shou/button01.png',
		'img/shou/button02.png',
		'img/shou/button03.png',
		'img/shou/shiyan.png',
		'img/shou/shou-bg02.png',
		'img/shou/shou-text.png',
		'img/kol/biaoti.png',
		'img/kol/go-back.png',
		'img/kol/kol-bg.png',
		'img/kol/kol-people01.png',
		'img/kol/kol-people02.png',
		'img/kol/kol-people03.png',
		'img/kol/kol-people04.png',
		'img/kol/kol-text.png',
		'img/kol/kol-text01.png',
		'img/kol/kol-text02.png',
		'img/kol/kol-text03.png',
		'img/kol/kol-text04.png',
		'img/car-content/car-page01/car-page-bg.png',
		'img/car-content/car-page01/up1.png',
		'img/car-content/car-page01/up2.png',
		'img/car-content/car-page02/car-page-bg.png',
		'img/car-content/car-page02/page02-2.png',
		'img/car-content/car-page02/page02-3.png',
		'img/car-content/car-page02/page02-text.png',
		'img/car-content/car-page02/page02-text02.png',
		'img/car-content/car-page03/car-page02.png',
		'img/car-content/car-page03/car-page03.png',
		'img/car-content/car-page03/car-page-bg.png',
		'img/car-content/car-page03/car-page-text01.png',
		'img/car-content/car-page04/car-page01.png',
		'img/car-content/car-page04/car-page02.png',
		'img/car-content/car-page04/car-page-bg.png',
		'img/car-content/car-page04/car-page-text01.png',
		'img/car-content/car-page04/car-page-text02.png',
		'img/car-content/car-page05/car-page011.png',
		'img/car-content/car-page05/car-page02.png',
		'img/car-content/car-page05/car-page05.png',
		'img/car-content/car-page05/car-page-bg.png',
		'img/car-content/car-page05/car-page-text.png',
	    'img/infom/chang.png',
	    'img/infom/chang-car.png',
	    'img/infom/chang-sec.png',
	    'img/infom/icon-01.png',
	    'img/infom/icon-02.png',
	    'img/infom/icon-03.png',
	    'img/infom/icon-04.png',
	    'img/infom/icon-05.png',
	    'img/infom/inform.png',
	    'img/infom/submit.png',
	    'img/infom/text.png',
	    'img/go-back.png',
	    'img/one-font.png',
	    'img/shu.png',
	    'img/share.jpg',
	    'img/video.png'
	];
	ImgLoadingByFile(imgFile,'loadingPage','img-loading-txt');
	var w = window.innerWidth;
	var h = window.innerHeight;
	ProvinceData.init("ddlProvince","ddlCity");
	SaveInfo.init();
});
var SaveInfo = {
    username:null,//name,name
    sex:"男",
    phone:null,//mobile,mobile
    cartype:null,//interested,car_type
    province:null,//province,dealer_name省份，城市，经销商（1,2,3）
    city:null,//city,无
    source:null,//source,source,123
    checked:true,
    init:function(){
       SaveInfo.updateView();
	     function GetQueryString(name){
	            var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
	            var r = window.location.search.substr(1).match(reg);
	            if(r!=null&&r!=undefined)return  unescape(r[2]); return null;
	     }
        SaveInfo.source = GetQueryString('hmsr');           
    },
    updateView:function(){
        SaveInfo.inputReg();
        SaveInfo.submit();
        $('select').on('touchstart',function(){
            $(this).find('option[value="-1"]').attr('disabled','disabled');
        });
        $('select').change(function(){
            $(this).addClass('changed');
        })
    },
    inputReg:function(){
        $('input[name="username"]').blur(function(){
            var val = $(this).val();
            var reg =/^[a-zA-Z\u4E00-\u9FA5]*$/;
            console.log(reg.test(val));
            if(val!=""&&val!="test"&&val!="空白"&&val!="Unknown"&&val!="未知"&&val!="未告知"&&this.validity.valid&&reg.test(val)){
                //$(this).parent().removeClass('red');
                $(this).attr('placeholder','姓名');
                $(this).removeClass('inputerror');
            }else{
                //$(this).parent().addClass('red');
                $(this).val('');
                $(this).attr('placeholder','请您正确输入姓名');
                $(this).addClass('inputerror');
            }
        });
        var nofirst = false;
        $('input[name="username"]').focus(function(){
            if(nofirst){
                if(this.validity.valid) {
                    //$('input[name="username"]').parent().removeClass('red');
                }else{
                    //$('input[name="username"]').parent().addClass('red');
                }
            }else{
                nofirst = true;
            }

        });
        $('input[name="phone"]').blur(function(){
            var reg = /^1[34578]\d{9}$/;
            var val = $(this).val();
            if(isNaN(parseFloat(val))){
                $(this).val('');
                //$(this).parent().addClass('red');
                $(this).attr('placeholder','请您正确输入手机号');
                $(this).addClass('inputerror');
            }else{
                if(reg.test(val)){
                    //$(this).parent().removeClass('red');
                    $(this).attr('placeholder','手机号');
                    $(this).removeClass('inputerror');

                }else{
                    $(this).val('');
                    //$(this).parent().addClass('red');
                    $(this).attr('placeholder','请您正确输入手机号');
                    $(this).addClass('inputerror');
                }
            }

        });
        $('input[name="phone"]').focus(function(){
            $(this).keyup(function(){
                if(this.validity.valid){
                    $(this).parent().removeClass('red');
                }else{
                    $(this).parent().addClass('red');
                }
            })
        });
        $('input[type=checkbox]').change(function(){
        	var check = $(this).attr('checked');
        	console.log(check);
        	if(check=='checked'){
        		$('#submit').removeClass('nosubmit');
        		SaveInfo.checked=true;
        	}else{
        		$('#submit').addClass('nosubmit');
        		SaveInfo.checked=false;
        	}
        })
    },
    clickReg:function(){
        var usernameReg = false,phoneReg = false,provinceReg = false,cityReg = falsecartypeReg = false;
        var errMsg = '';
        var inputUsername = document.getElementById('username');
        if(inputUsername.validity.valid){
            usernameReg = true;
        }else{
            usernameReg = false;
        }
        var reg = /^1[34578]\d{9}$/;
        if(reg.test($('input[name="phone"]').val())){
            phoneReg = true;
        }else{
            phoneReg = false;
        }
        function selectReg(selectName){
            var val = $('select[name='+selectName+'] option:selected').val();
            var reg;
            if(val&&val!=-1){
                reg = true;
            }else{
                reg = false;
            }
            return reg;

        }
        provinceReg = selectReg('ddlProvince');
        cityReg = selectReg('ddlCity');
        cartypeReg = selectReg('cartype');
        var total = usernameReg&&phoneReg&&provinceReg&&cityReg&&cartypeReg;
        console.log(usernameReg,phoneReg,provinceReg,cityReg,cartypeReg);
        console.log(total);
        //return total;
        return usernameReg&&phoneReg;
        //return true;
    },
    submit:function(){
        $('#submit').on('click',function(e){
            e.preventDefault();
            $(".alert").click(function(){
                $(".alertBox").fadeOut(300);
                $('.btn-userInfo').addClass('btn-move');
              
            });
            if(SaveInfo.checked){
            	
	            if(SaveInfo.clickReg()){
	           
	                SaveInfo.username = $('input[name="username"]').val();
	                SaveInfo.phone = $('input[name="phone"]').val();
	              
	                SaveInfo.cartype = $('select[name="cartype"] option:selected').val();
	                
	                SaveInfo.province = $('select[name="ddlProvince"] option:selected').val();
	                
	                SaveInfo.city = $('select[name="ddlCity"] option:selected').val();
	                
	                SaveInfo.dealerName = $('select[name="agency"] option:selected').val();
	                SaveInfo.sex = $('input[type=radio]:checked').val();
	                // 发起Ajax调用
	                var xyData = {
	                    name:SaveInfo.username,
	                    mobile:SaveInfo.phone,
	                    sex:SaveInfo.sex,
	                    car_type:SaveInfo.cartype,
	                    dealer_name:SaveInfo.province+','+SaveInfo.city,
	                    source:SaveInfo.source
	                };
	                console.log(xyData);
	                $.ajax({
	                    type:'get',
	                    url:'https://h5php.xingyuanauto.com/Flow/public/index.php/port/Usercacelotter/UserLotter',
	                    data:xyData,
	                    dataType:'json',
	                    success:function(msg){
	                        console.log(msg);
	                        if(msg.code==1001){
	                        	alert('预约成功');
	                            $(".success").show();
	                            $('.btn-userInfo').removeClass('btn-move');
	                            $('select option[value="-1"]').attr('disabled',false);
	                            $('#userForm')[0].reset();
	                            $('select').removeClass('changed');
	                            //$('#submit').addClass('nosubmit');
	                            //SaveInfo.checked=false;
	                          }else if(msg.code==1003){
	                          	
	                          	alert('手机号已注册');
	                          }else{
	                          	alert('预约失败');
	                          }
	                    }
	                });
	            }else{
	                //$(".error").show();
	                alert('姓名和手机号不能为空');
	            }
             }else{
             	alert('请阅读条款');
             }
        });
    }
};	